#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>



// 用法：./server
int main(int argc, char const* argv[])
{
    
    int server_socket;
    server_socket = socket(AF_INET,SOCK_DGRAM,0);
    if (server_socket==-1)
    {
        perror("socket err\n");
        return -1;
    }
    
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(8888);
    addr.sin_addr.s_addr=INADDR_ANY;

    if(bind(server_socket,(struct sockaddr*)&addr,sizeof(addr))==-1)
    {
        perror("bind err\n");
        close(server_socket);
        return -1;
    }

    struct sockaddr_in client_addr;
    int addrlen = sizeof(client_addr);   

    char buf[64]={'\0'};    
    int count=0;
    struct sockaddr_in addr[100]={'\0'};
     
    while (1)
    {
        memset(buf,0,64);
        ssize_t len=recvfrom(server_socket,buf,64,0,(struct sockaddr*)&client_addr,&addrlen);
        if (len>0)
        {
            printf("recv data = %s\n",buf);
            for (int i = 0; i < count; i++)
            {
                if(strcmp(addr[i],client_addr)==0)
                {
                    break;
                }
                if(i==count-1)
                {
                    strcpy(client_addr,addr[count]);
                    count++;
                }
            }
            
            for (int j = 0; j < count; j++)
            {
                sendto(server_socket,buf,64,0,(struct sockaddr*)&addr[j],addrlen);
            }
            
        }
        
    }
    close(server_socket);
    
    return 0;
}